<template>
  <el-dialog
    v-model="visible"
    :title="status ? '查看商品' : '选择商品'"
    width="55%"
    top="50px"
    class="group-dialog"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    :modal="false"
  >
    <el-table
      ref="multipleTableRef"
      :data="tableData"
      border
      :header-cell-style="{
        background: '#EEF3FF',
        color: '#333333'
      }"
      tooltip-effect="dark"
      style="width: 100%"
      row-key="skuId"
      max-height="600"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        v-if="status"
        type="selection"
        :reserve-selection="true"
        width="55"
      />
      <el-table-column label="商品信息" width="150" align="center">
        <template #default="scope">
          <img height="80" width="80" :src="scope.row.image" alt srcset />
        </template>
      </el-table-column>
      <el-table-column prop="productName" label="" />
      <el-table-column
        prop="originalPrice"
        label="原价（元）"
        width="120"
      />
      <el-table-column prop="value" label="规格" width="120" />
      <el-table-column label="折扣" width="155">
        <template #default="scope">
          <el-input-number
            v-model="scope.row.discount"
            :disabled="!status"
            size="small"
            :controls="false"
            :precision="1"
            :max="9.9"
            :min="0.1"
            maxlength="2"
            @blur="blurInput(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="活动价（元）">
        <template #default="scope">
          <span
            v-if="
              scope.row.discount < 10 &&
                scope.row.discount !== null &&
                scope.row.discount !== ''
            "
          >{{
            numFilter((scope.row.discount / 10) * scope.row.originalPrice)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="stockNumber"
        label="库存"
        width="120"
        show-overflow-tooltip
      />
    </el-table>
    <el-pagination
      :current-page="page.page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="page.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
      style="justify-content: flex-end; margin: 20px 0;"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <template #footer>
      <el-button
        v-if="status"
        type="primary"
        @click="handleCheck"
      >确 定</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, shallowRef, toRefs } from 'vue';
import {
  getDisProList,
} from '@/api/marketing';

const props = defineProps({
  /** 0查看  1 创建 2编辑 */
  status: {
    type: Number,
    default: 0
  }
})
const emits = defineEmits(['selected'])
let visible = shallowRef(false);

let { status } = toRefs(props);
let tableData = ref([]);
let multipleSelection = ref([]);

let page = reactive({
  page: 1,
  pageSize: 10,
  total: 10,
})
let query = reactive({
  activityId: null
})
let inputDiscountTableData = ref([]);

function show (arg = {
  id: null,
}) {
  let { id } = arg
  if (id) {
    query.activityId = id
  }
  visible.value = true
  getProductList();
}

function getProductList () {
  getDisProList({
    page: page.page,
    pageSize: page.pageSize,
    ...query
  }).then((res) => {
    if (res.code === '') {
      let dataList = res.data && res.data.list || [];
      if (inputDiscountTableData.value.length > 0) {
        dataList.forEach((item) => {
          const index = inputDiscountTableData.value.findIndex(
            (cItem) => cItem.skuId === item.skuId
          );
          if (index !== -1) {
            item.discount = inputDiscountTableData.value[index].discount;
          }
        });
      }
      tableData.value = dataList;
      page.total = res.data.total;
    }
  });
}
function handleCurrentChange (val) {
  page.page = val
  getProductList();
}

function handleSizeChange (val) {
  page.page = 1;
  page.pageSize = val;
  getProductList();
}

function handleSelectionChange (val) {
  multipleSelection.value = val;
}

function handleClose () {
  visible.value = false
}

function handleCheck () {
  let idList = [];
  multipleSelection.value.forEach((i) => {
    let discountPrice = null;
    if (i.discount < 10) {
      discountPrice = (i.discount / 10) * i.originalPrice;
    } else {
      discountPrice = (i.discount / 100) * i.originalPrice;
    }
    idList.push({
      price: discountPrice,
      discount: i.discount,
      productId: i.productId,
      skuId: i.skuId,
    });
  });
  emits('selected', idList)
  handleClose();
}

function numFilter (value) {
  return parseFloat(value).toFixed(2);
}
defineExpose({
  show,
  handleClose
})
</script>